package com.koron.standard.deviceBrand.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.WorkbookUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.koron.bean.base.Response;
import com.koron.standard.bean.query.PageQuery;
import com.koron.standard.deviceBrand.bean.po.BrandStock;
import com.koron.standard.deviceBrand.bean.query.BrandQuery;
import com.koron.standard.deviceBrand.excel.BrandStockListener;
import com.koron.standard.deviceBrand.service.BrandStockService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;

/**
 * 设备品牌库(BrandStock)表控制层
 *
 * @author jzp
 * @since 2022-01-13
 */
@Api(tags = "设备品牌库接口")
@RestController
@RequestMapping("/brandStock")
public class BrandStockController {

    @Autowired
    private BrandStockService brandStockService;

    @ApiOperation(value = "分页")
    @GetMapping("page")
    public Response<Page<BrandStock>> page(PageQuery<BrandStock> pageQuery, BrandQuery brandQuery) {
        // 默认按频率降序查询
        if (CollectionUtils.isEmpty(pageQuery.getOrders())) {
            pageQuery.setOrders(Collections.singletonList(OrderItem.desc("num")));
        }
        Page<BrandStock> page = pageQuery.convertPage();
        LambdaQueryWrapper<BrandStock> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotEmpty(brandQuery.getKeyword()), BrandStock::getName, brandQuery.getKeyword())
                .or().like(StrUtil.isNotEmpty(brandQuery.getKeyword()), BrandStock::getFactoryName, brandQuery.getKeyword());
        brandStockService.page(page, wrapper);
        return Response.succ(page, page.getTotal());
    }

    @ApiOperation(value = "根据id查询")
    @GetMapping
    public Response<BrandStock> select(@RequestParam String id) {
        BrandStock brandStock = brandStockService.getById(id);
        return Response.ok(brandStock);
    }

    @ApiOperation(value = "保存")
    @PostMapping
    public Response<String> save(@RequestBody BrandStock brandStock) {
        Assert.isTrue(brandStockService.countName(brandStock) == 0, "品牌简称不允许重复");
        brandStockService.save(brandStock);
        return Response.ok(brandStock.getId());
    }

    @ApiOperation(value = "修改")
    @PutMapping
    public Response<String> update(@RequestBody BrandStock brandStock) {
        Assert.isTrue(brandStockService.countName(brandStock) <= 1, "品牌简称不允许重复");
        brandStockService.updateById(brandStock);
        return Response.ok(brandStock.getId());
    }

    @ApiOperation(value = "频率+1")
    @PutMapping("numPlus")
    public Response numPlus(String id) {
        UpdateWrapper<BrandStock> wrapper = new UpdateWrapper<>();
        wrapper.setSql("num=num+1");
        wrapper.eq("id", id);
        brandStockService.update(wrapper);
        return Response.ok();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping
    public Response delete(@RequestParam String id) {
        brandStockService.removeById(id);
        return Response.ok();
    }

    @SneakyThrows
    @ApiOperation(value = "下载模板")
    @GetMapping("template")
    public void template(HttpServletResponse response) {
        String path = "excel/brand_stock_standard.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        Workbook book = WorkbookUtil.createBook(classPathResource.getInputStream());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("品牌库", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        book.write(response.getOutputStream());
    }

    @SneakyThrows
    @ApiOperation(value = "导入")
    @PostMapping("import")
    public Response importFile(@RequestParam("file") MultipartFile file) {
        EasyExcel.read(file.getInputStream(), BrandStock.class, new BrandStockListener(brandStockService))
                .sheet("品牌库")
                .headRowNumber(1)
                .doRead();

        return Response.ok("导入成功", null);
    }

    @SneakyThrows
    @ApiOperation(value = "导出", notes = "根据条件导出查询出的所有数据")
    @GetMapping("export")
    public void exportFile(HttpServletResponse response, BrandQuery brandQuery) {
        String path = "excel/brand_stock_standard.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("品牌库", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 默认按频率降序查询
        LambdaQueryWrapper<BrandStock> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotEmpty(brandQuery.getKeyword()), BrandStock::getName, brandQuery.getKeyword())
                .or().like(StrUtil.isNotEmpty(brandQuery.getKeyword()), BrandStock::getFactoryName, brandQuery.getKeyword());
        List<BrandStock> list = brandStockService.list(wrapper);

        EasyExcel.write(response.getOutputStream())
                .withTemplate(classPathResource.getInputStream())
                .needHead(false)
                .sheet("品牌库")
                .doWrite(list);
    }

}
